<template>
  <section class="f-equipment-add w-card">
    <div class="title-box">
      <span class="title-text">{{ isEdit? '编辑': '新增'}}设备</span>
      <div v-if="!isEdit">
        <el-button @click="reset()">重置</el-button>
        <el-button type="primary" @click="submitHandle('add')">确定创建设备</el-button>
      </div>
      <div v-else>
        <el-button @click="cancelEdit()">取消编辑</el-button>
        <el-button type="primary" @click="submitHandle('modify')">确定重新发布设备</el-button>
      </div>
    </div>

    <section class="f-content">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <el-row>
          <el-col :span="7">
            <el-form-item label="设备商品名称:" prop="goodsName">
              <el-input v-model="ruleForm.goodsName" placeholder="请输入设备商品名称" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="设备型号:" prop="equipmentType">
              <el-select v-model="ruleForm.equipmentType" clearable :disabled="isEdit">
                <el-option v-for="(item,index) in modelList" :label="item.equipmentType" :value="item.equipmentType"
                  :key="index" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="设备颜色:">
              <el-input v-model="ruleForm.color" placeholder="请输入设备颜色" :disabled="isEdit" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7">
            <el-form-item label="标价（元）:" prop="showPrice">
              <el-input v-model="ruleForm.showPrice" type="number" placeholder="请输入标价" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="售价（元）:" prop="actualPrice">
              <el-input v-model="ruleForm.actualPrice" type="number" placeholder="请输入售价" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="激活积分:" prop="activePoints">
              <el-input v-model="ruleForm.activePoints" placeholder="请输入激活积分" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7">
            <el-form-item label="套餐:" prop="packageName">
              <el-select v-model="ruleForm.packageName" clearable :disabled="isEdit">
                <el-option v-for="(item,index) in packList" :label="item.packageName" :value="item.packageName" :key="index" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="同级推荐佣金（元）:" prop="tuijianIncome">
              <el-input v-model="ruleForm.tuijianIncome" type="number" placeholder="请输入同级推荐佣金" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="分红/排行榜:" prop="joinFenhong">
              <el-radio-group v-model="ruleForm.joinFenhong">
                <el-radio :label="1">参与</el-radio>
                <el-radio :label="0">不参与</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7">
            <el-form-item label="分润佣金配置:" prop="funrunIncome">
              <el-radio-group v-model="ruleForm.funrunIncome">
                <el-radio :label="1">分佣</el-radio>
                <el-radio :label="0">不分佣</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="备注信息:">
              <el-input v-model="ruleForm.remark" :rows="3" type="textarea" placeholder="请输入备注信息" />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="f-card" v-if="ruleForm.funrunIncome == 1">
          <p class="f-title">分润佣金配置</p>
          <el-row>
            <el-col :span="5">
              <el-form-item label="实时佣金（元）:" prop="baseIncome">
                <el-input v-model="ruleForm.funrunIncomeConf.baseIncome" type="number" placeholder="请输入实时佣金" />
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="实时结算佣金名称:" prop="baseIncomeName">
                <el-input v-model="ruleForm.funrunIncomeConf.baseIncomeName" placeholder="请输入实时结算佣金名称" />
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="月结级差佣金名称:" prop="monthIncomeName">
                <el-input v-model="ruleForm.funrunIncomeConf.monthIncomeName" placeholder="请输入月结级差佣金名称" />
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="分润佣金时机:" prop="incomeRunState">
                <el-select v-model="ruleForm.funrunIncomeConf.incomeRunState" clearable>
                  <el-option label="激活" :value="1" />
                  <el-option label="首充" :value="2" />
                  <el-option label="激活且首充" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="5">
              <el-form-item label="Lv1级差佣金（元）:" prop="buchongIncomeL1">
                <el-input v-model="ruleForm.funrunIncomeConf.buchongIncomeL1" type="number" placeholder="请输入Lv1级差佣金" />
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="Lv2级差佣金（元）:" prop="buchongIncomeL2">
                <el-input v-model="ruleForm.funrunIncomeConf.buchongIncomeL2" type="number" placeholder="请输入Lv2级差佣金" />
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="Lv3级差佣金（元）:" prop="buchongIncomeL3">
                <el-input v-model="ruleForm.funrunIncomeConf.buchongIncomeL3" type="number" placeholder="请输入Lv3级差佣金" />
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="Lv4级差佣金（元）:" prop="buchongIncomeL4">
                <el-input v-model="ruleForm.funrunIncomeConf.buchongIncomeL4" type="number" placeholder="请输入Lv4级差佣金" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="5">
              <el-form-item label="Lv5级差佣金（元）:" prop="buchongIncomeL5">
                <el-input v-model="ruleForm.funrunIncomeConf.buchongIncomeL5" type="number" placeholder="请输入Lv5级差佣金" />
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="Lv6级差佣金（元）:" prop="buchongIncomeL6">
                <el-input v-model="ruleForm.funrunIncomeConf.buchongIncomeL6" type="number" placeholder="请输入Lv6级差佣金" />
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="Lv7级差佣金（元）:" prop="buchongIncomeL7">
                <el-input v-model="ruleForm.funrunIncomeConf.buchongIncomeL7" type="number" placeholder="请输入Lv7级差佣金" />
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="Lv8级差佣金（元）:" prop="buchongIncomeL8">
                <el-input v-model="ruleForm.funrunIncomeConf.buchongIncomeL8" type="number" placeholder="请输入Lv8级差佣金" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="5">
              <el-form-item label="Lv9级差佣金（元）:" prop="buchongIncomeL9">
                <el-input v-model="ruleForm.funrunIncomeConf.buchongIncomeL9" type="number" placeholder="请输入Lv9级差佣金" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-form-item label="设备主图:" prop="roleName">
          <el-upload class="f-img-uploader" :action="uploadForm.action" :headers="uploadForm.headers" :data="uploadForm.data"
            :show-file-list="false" :on-success="uploadSuccess">
            <img v-if="ruleForm.headImg" :src="ruleForm.headImg" class="f-img" />
            <el-icon v-else class="f-img-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item class="f-mt-20" label="设备商品详情:" prop="roleName">
          <Editor width="100%" v-model="ruleForm.goodsDetail" :api-key="apiKey" :init="init" />
        </el-form-item>

      </el-form>
    </section>
  </section>
</template>
  
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStateStore } from '@/store'
import Editor from "@tinymce/tinymce-vue";
import api from './api.js'
import { errorDeal, getStore, successDeal } from '@/utils/utils.js';
import axios from 'axios';

export default {
  components: {
    Editor,
  },

  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    goodsInfo: {
      type: Object,
      default: {}
    }
  },

  emits: ["cancelEdit", "baseGoodsModify"],

  setup(props, context) {
    const store = useStateStore()

    const router = useRouter()
    const route = useRoute();

    const ruleFormRef = ref(null)

    const state = reactive({
      ruleForm: {
        joinFenhong: 0,
        funrunIncome: 0,
        funrunIncomeConf: {}
      },
      rules: {
        activePoints: [
          { required: true, message: "请输入激活积分", trigger: "blur" },
        ],
        actualPrice: [
          { required: true, message: "请输入设备售价", trigger: "blur" },
        ],
        equipmentType: [
          { required: true, message: "请输入设备型号", trigger: "blur" },
        ],
        goodsName: [
          { required: true, message: "请输入设备商品名称", trigger: "blur" },
        ],
        showPrice: [
          { required: true, message: "请输入设备标价", trigger: "blur" },
        ],
        tuijianIncome: [
          { required: true, message: "请输入同级推荐佣金", trigger: "blur" },
        ],
        packageName: [
          { required: true, message: "请选择套餐", trigger: "change" },
        ],

        // baseIncome: [
        //   { required: true, message: "请输入实时佣金", trigger: "blur" },
        // ],
        // baseIncomeName: [
        //   { required: true, message: "请输入实时结算佣金名称", trigger: "blur" },
        // ],
        // buchongIncomeL1: [
        //   { required: true, message: "请输入Lv1级差佣金", trigger: "blur" },
        // ],
        // buchongIncomeL2: [
        //   { required: true, message: "请输入Lv2级差佣金", trigger: "blur" },
        // ],
        // buchongIncomeL3: [
        //   { required: true, message: "请输入Lv3级差佣金", trigger: "blur" },
        // ],
        // buchongIncomeL4: [
        //   { required: true, message: "请输入Lv4级差佣金", trigger: "blur" },
        // ],
        // buchongIncomeL5: [
        //   { required: true, message: "请输入Lv5级差佣金", trigger: "blur" },
        // ],
        // buchongIncomeL6: [
        //   { required: true, message: "请输入Lv6级差佣金", trigger: "blur" },
        // ],
        // buchongIncomeL7: [
        //   { required: true, message: "请输入Lv7级差佣金", trigger: "blur" },
        // ],
        // buchongIncomeL8: [
        //   { required: true, message: "请输入Lv8级差佣金", trigger: "blur" },
        // ],
        // buchongIncomeL9: [
        //   { required: true, message: "请输入Lv9级差佣金", trigger: "blur" },
        // ],
        // monthIncomeName: [
        //   { required: true, message: "请输入月结级差佣金名称", trigger: "blur" },
        // ],
        // incomeRunState: [
        //   { required: true, message: "请选择分润佣金时机", trigger: "change" },
        // ],
      },

      uploadForm: {
        action: '/ums/file/upload/user/pub',
        headers: {
          Authorization: getStore('USER_AUTHOR_INRE').Authorization || `'','','',3,20,''`,
          Token: `Bearer ${window.localStorage.getItem("USER_TOKEN_INRE")}`,
          platformHeadType: 'rcmsPlatform'
        },
        data: {}
      },

      packList: [],
      modelList: [],
    })

    onMounted(() => {
      getPackageChooseList()
      getModelChooseList()
      if (props.isEdit) {
        state.ruleForm = JSON.parse(JSON.stringify(props.goodsInfo))
      }
    })

    function submitHandle(type) {
      ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          let json = JSON.parse(JSON.stringify(state.ruleForm))
          if (json.funrunIncome == 0) {
            json.funrunIncomeConf = {}
          }

          if (type == 'add') {
            api.baseGoodsCreate(json).then(res => {
              successDeal('新增成功！')
              setTimeout(() => {
                router.go(-1)
              }, 500)
            })
          } else if (type == 'modify') {
            let json = JSON.parse(JSON.stringify(state.ruleForm))
            if (json.funrunIncome == 0) {
              json.funrunIncomeConf = {
                baseIncomeName: ''
              }
            }
            api.baseGoodsModify(json).then(res => {
              successDeal('编辑成功！')
              context.emit('baseGoodsModify')
            })
          }
        }
      })
    }

    const cancelEdit = () => {
      context.emit('cancelEdit')
    }

    const uploadSuccess = (res) => {
      if (res.code == '200') {
        state.ruleForm.headImg = res.data.ossUrl
        ruleFormRef.value.validate()
      } else {
        errorDeal(res.msg)
      }
    }

    const reset = () => {
      state.ruleForm = {
        joinFenhong: 0,
        funrunIncomeConf: 0,
      }
      ruleFormRef.value.resetFields()
    }

    const getPackageChooseList = () => {
      api.packageChooseList().then(res => {
        state.packList = res.data.list
      })
    }

    const getModelChooseList = () => {
      api.modelChooseList().then(res => {
        state.modelList = res.data.list
      })
    }

    const tiny = reactive(
      {
        content: '',
        // apiKey: "g8c1pwjwbow02qaborhe09f1rkrrm49po9wp4e3sp80ixx3g",
        apiKey: "g8c1pwjwbow02qaborhe09f1rkrrm49po9wp4e3sp80ixx3g",
        init: {
          language: "zh_CN",
          placeholder: "在这里输入文字",
          min_width: 320,
          min_height: 220,
          height: 500,
          resize: "both",
          branding: false,

          font_formats:
            "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;", //字体样式
          plugins:
            "print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave emoticons", //插件配置 axupimgs indent2em
          toolbar: [
            "fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | bullist numlist | blockquote subscript superscript removeformat ",
            "styleselect formatselect fontselect fontsizeselect |  table image axupimgs media emoticons charmap hr pagebreak insertdatetime  selectall visualblocks searchreplace | code print preview | indent2em lineheight formatpainter",
          ],
          images_upload_url: '/ums/file/upload/user/pub',
          paste_data_images: false,
          images_upload_handler: (blobInfo, success, failure) => {
            const myBlob = blobInfo.blob()
            let param = new FormData()
            param.append('file', myBlob, Math.random() * 1000000 + 1 + '.jpg')
            const token = window.localStorage.getItem("USER_TOKEN_INRE") || '';
            const uesrInfo = getStore("USER_INFO_INRE") || {};
            const Authorization = getStore("USER_AUTHOR_INRE") || {
              Authorization: `'','','',3,20,''`,
            };
            let config = {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: token ? `Bearer ${token}` : '',
                username: uesrInfo.username || '',
                Authorization: Authorization.Authorization,
                platformHeadType: 'rcmsPlatform',
              }
            }
            axios.post('/ums/file/upload/user/pub', param, config).then(res => {
              if (res.data.code == '200') {
                success(res.data.data.ossUrl)
              } else {
                warningDeal(res.data.msg)
              }
            }).catch(err => {
              console.log(err)
            })
          },

          file_picker_types: "file image media",
          // 文件上传处理函数
          file_picker_callback: function (callback, value, meta) {
            let filetype;
            if (meta.filetype == "image") {
              filetype = ".jpg, .jpeg, .png, .gif, .ico, .svg";
            } else if (meta.filetype == "media") {
              filetype = ".mp3, .mp4, .avi, .mov";
            } else {
              filetype =
                ".pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4, .jpg, .jpeg, .png, .gif, .ico, .svg";
            }
            let inputElem = document.createElement("input")
            inputElem.setAttribute("type", "file")
            inputElem.setAttribute("accept", filetype)
            inputElem.click()
            inputElem.onchange = () => {
              state.loading = true
              let file = inputElem.files[0];
              let param = new FormData()
              param.append('file', file, file.name)
              const token = window.localStorage.getItem("USER_TOKEN_INRE") || '';
              const uesrInfo = getStore("USER_INFO_INRE") || {};
              const Authorization = getStore("USER_AUTHOR_INRE") || {
                Authorization: `'','','',3,20,''`,
              };
              let config = {
                headers: {
                  'Content-Type': 'multipart/form-data',
                  token: token ? `Bearer ${token}` : '',
                  username: uesrInfo.username || '',
                  Authorization: Authorization.Authorization,
                  platformHeadType: 'rcmsPlatform',
                }
              }
              axios.post('/ums/file/upload/user/pub', param, config).then(res => {
                if (res.data.code == '200') {
                  callback(res.data.data.ossUrl, { title: file.name })
                } else {
                  warningDeal(res.data.msg)
                }
                state.loading = false
              }).catch(err => {
                console.log(err)
                state.loading = false
              })
            }
          },
        },
      }
    )

    return {
      ...toRefs(state),
      ...toRefs(tiny),
      ruleFormRef,
      submitHandle,
      cancelEdit,
      uploadSuccess,
      reset,
    }
  }
}
  </script>
  
<style lang='scss' scoped>
.f-equipment-add {
  box-sizing: border-box;
  padding: 20px;
  height: 100%;
  > .title-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30px;
    > .title-text {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .f-content {
    padding-left: 5px;
    .f-title {
      font-weight: bold;
      font-size: 15px;
      color: #000000;
      border-bottom: 1px solid #eaeaea;
      padding-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .f-tips {
        color: #f73e3e;
        font-size: 12px;
        font-weight: 500;
        margin-left: 40px;
      }
    }
    .f-tabel {
      border: 1px solid #acacac;
      width: 800px;
    }
    .f-guige-box {
      font-size: 14px;
      color: #404040;
      background: #eef2f4;
      display: flex;
      align-items: center;
      padding: 16px 10px;
      margin-top: 20px;
    }
  }
  .f-card {
    background: #f1f4f6;
    border-radius: 6px;
    padding: 20px;
    margin-top: 18px;
    .f-title {
      font-weight: 400;
      font-size: 16px;
      color: #000000;
      margin-bottom: 25px;
      display: flex;
      justify-content: space-between;
    }
    :deep(.el-form-item) {
      display: flex !important;
    }
  }
}
</style>

<style>
.f-img-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.f-img-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.f-img-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 125px;
  height: 125px;
  text-align: center;
}
.f-img {
  width: 125px;
  height: 125px;
}
</style>